package com.hyt.it.ogt.kq.service.gov.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.service.gov.mapper.BreakRuleBehaviorMapper;
import com.hyt.it.ogt.kq.service.gov.model.entity.BreakRuleBehavior;
import com.hyt.it.ogt.kq.service.gov.service.IBreakRuleBehaviorService;
import com.hyt.it.ogt.kq.service.gov.service.IBreakRuleSchemeService;
import com.hyt.it.ogt.kq.service.gov.service.IOfficeBreakRuleBehaviorService;
import com.hyt.it.ogt.kq.service.gov.service.ITaskService;
import com.hyt.it.ogt.kq.common.gov.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 违纪行为表 服务实现类
 * </p>
 *
 * @author huangyh
 * @since 2021-03-08
 */
@Service
public class BreakRuleBehaviorServiceImpl extends BaseServiceImpl<BreakRuleBehaviorMapper, BreakRuleBehavior> implements IBreakRuleBehaviorService {

    @Resource
    private IOfficeBreakRuleBehaviorService iOfficeBreakRuleBehaviorService;

    @Autowired
    private IBreakRuleSchemeService iBreakRuleSchemeService;

    @Resource
    private ITaskService iTaskService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBehavior(BreakRuleBehavior param) {
        //: 校验任务数据锁定状态(后续版本考虑优化为从缓存中获取状态)
        iTaskService.isLockDataThrowException(param.getTaskId());
        //参数校验
        this.verifyBehavior(param);
        try {
            //更新违纪行为
            super.updateById(param);
        } catch (DuplicateKeyException e) {
            throw new KqException(ResponseCode.BEHAVIOR_SCHEME_CODE_EXIST_IN_TASK_ID.getCode(),ResponseCode.BEHAVIOR_SCHEME_CODE_EXIST_IN_TASK_ID.getMsg());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBehavior(BreakRuleBehavior param) {
        //: 校验任务数据锁定状态(后续版本考虑优化为从缓存中获取状态)
        iTaskService.isLockDataThrowException(param.getTaskId());
        //参数校验
        this.verifyBehavior(param);
        //插入数据库
        super.save(param);
    }

    protected void verifyBehavior(BreakRuleBehavior breakRuleBehavior) throws KqException {
        //校验违纪行为代码是否是1~10位
        String code = breakRuleBehavior.getCode();
        if (!iBreakRuleSchemeService.checkCode(code)) {
            //违纪行为代码必须是1~10位
            throw new KqException(ResponseCode.BEHAVIOR_CODE_FORMAT_INVALID.getCode(),ResponseCode.BEHAVIOR_CODE_FORMAT_INVALID.getMsg());
        }
        LambdaQueryWrapper<BreakRuleBehavior> query = Wrappers.<BreakRuleBehavior>lambdaQuery()
                .eq(BreakRuleBehavior::getTaskId, breakRuleBehavior.getTaskId())
                .eq(BreakRuleBehavior::getCode, breakRuleBehavior.getCode());
        if(StringUtils.isNotBlank(breakRuleBehavior.getId())) {
            query.ne(BreakRuleBehavior::getId, breakRuleBehavior.getId());
        }
        //校验当前考试任务下是否存在相同的违纪行为代码
        int count = super.count(query);
        if (count > 0) {
            //当前考试任务下存在相同的违纪行为代码
            throw new KqException(ResponseCode.BEHAVIOR_SCHEME_CODE_EXIST_IN_TASK_ID.getCode(), ResponseCode.BEHAVIOR_SCHEME_CODE_EXIST_IN_TASK_ID.getMsg());
        }
        //校验违纪处理方法代码是否存在
        if (iBreakRuleSchemeService.getById(breakRuleBehavior.getSchemeId()) == null) {
            //违纪处理方法不存在
            throw new KqException(ResponseCode.BEHAVIOR_SCHEME_NON_EXIST.getCode(),ResponseCode.BEHAVIOR_SCHEME_NON_EXIST.getMsg());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBehavior(String ids) {
        //ids字符串转list
        List<String> behaviorIds = StringUtil.stringToList(ids);
        //: 校验任务数据锁定状态(后续版本考虑优化为从缓存中获取状态)
        String taskId = this.lambdaQuery()
                .eq(BreakRuleBehavior::getId, behaviorIds.get(0))
                .eq(BreakRuleBehavior::getDelFlag, false)
                .last("LIMIT 1")
                .one()
                .getTaskId();
        iTaskService.isLockDataThrowException(taskId);
        //删除违纪行为
        super.removeByIds(behaviorIds);
    }

    /**
     * 初始化数据，默认从机构级别的数据拉取
     * @param taskId
     * @param officeId
     */
    @Override
    public void initBreakRuleBehaviorFromOffice(String taskId, String officeId) {

        Integer count = this.lambdaQuery()
                .eq(BreakRuleBehavior::getTaskId,taskId)
                .eq(BreakRuleBehavior::getDelFlag,false)
                .count();
        if (count <= 0) {
            //1.机构数据初始化
            iOfficeBreakRuleBehaviorService.initOfficeBreakRuleBehaviorFromOffice(officeId);
            //2.任务数据初始化
            baseMapper.initBreakRuleBehaviorFromOffice(taskId,officeId);

        }
    }

    @Override
    public List<BreakRuleBehavior> listByTaskId(String taskId) {
        QueryWrapper<BreakRuleBehavior> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(BreakRuleBehavior::getTaskId, taskId)
                .eq(BreakRuleBehavior::getDelFlag, false);
        return list(queryWrapper);
    }

}
